<template>
  <div class="ivr-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-icon">
            <Icon icon="ep:phone" />
          </div>
          <div class="header-info">
            <h1 class="page-title">数字人流程</h1>
            <p class="page-subtitle">管理和配置语音交互流程</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-layout">
      <!-- 左侧分组树 -->
      <div class="sidebar-section">
        <div class="sidebar-content">
          <!-- 添加分组按钮 -->
          <div class="add-group-section">
            <div class="add-group-btn" @click="addGroup">
              <Icon icon="ep:plus" class="add-icon" />
              <span class="add-text">增加分组</span>
            </div>
          </div>

          <!-- 分组树 -->
          <div class="tree-section">
            <div class="tree-header">
              <Icon icon="ep:folder" class="tree-header-icon" />
              <span class="tree-title">分组列表</span>
            </div>

            <div class="tree-container">
              <el-tree
                :props="{ label: 'title' }"
                :data="groupList"
                node-key="id"
                highlight-current
                ref="treeRefs"
                @current-change="handleCheckChange"
                :expand-on-click-node="false"
                class="group-tree"
              >
                <template #default="{ data }">
                  <div class="tree-node">
                    <div class="node-content">
                      <Icon icon="ep:folder" class="node-icon" />
                      <span class="node-title">{{ data.title }}</span>
                    </div>
                    <div class="node-actions">
                      <el-button type="danger" text @click.stop="delTree(data)" class="delete-btn">
                        <Icon icon="ep:delete" />
                      </el-button>
                    </div>
                  </div>
                </template>
              </el-tree>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div class="content-section">
        <div class="content-wrapper">
          <!-- 操作栏 -->
          <div v-if="changeGroupItem" class="action-bar">
            <div class="action-left">
              <div class="current-group">
                <Icon icon="ep:folder-opened" class="group-icon" />
                <span class="group-name">{{ changeGroupItem.title }}</span>
              </div>
            </div>
            <div class="action-right">
              <el-button type="primary" @click="addIvr" class="add-ivr-btn">
                <Icon icon="ep:plus" class="btn-icon" />
                新增流程
              </el-button>
            </div>
          </div>

          <!-- IVR列表 -->
          <div class="table-section">
            <div v-if="ivrList.length" class="table-container">
              <el-table :data="ivrList" class="ivr-table">
                <el-table-column prop="name" label="名称" min-width="150">
                  <template #default="scope">
                    <div class="name-cell">
                      <div class="name-icon">
                        <Icon icon="ep:connection" />
                      </div>
                      <span class="name-text">{{ scope.row.name }}</span>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="desc" label="描述" min-width="200" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="desc-cell">
                      <span class="desc-text">{{ scope.row.desc }}</span>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column prop="status" label="状态" width="100" align="center">
                  <template #default="scope">
                    <el-tag :type="statusObj[scope.row.status]?.type" class="status-tag">
                      <Icon :icon="getStatusIcon(scope.row.status)" class="tag-icon" />
                      {{ statusObj[scope.row.status]?.label }}
                    </el-tag>
                  </template>
                </el-table-column>

                <el-table-column prop="creatorName" label="创建人" width="120" align="center">
                  <template #default="scope">
                    <div class="creator-cell">
                      <Icon icon="ep:user" class="creator-icon" />
                      <span>{{ scope.row.creatorName }}</span>
                    </div>
                  </template>
                </el-table-column>

                <el-table-column
                  label="创建时间"
                  align="center"
                  prop="createTime"
                  :formatter="dateFormatter"
                  width="180"
                />

                <el-table-column label="操作" align="center" width="300" fixed="right">
                  <template #default="scope">
                    <div class="action-buttons">
                      <el-button type="primary" text @click="edit(scope.row)" class="action-btn">
                        <Icon icon="ep:edit" class="btn-icon" />
                        编辑
                      </el-button>

                      <el-button
                        type="success"
                        text
                        v-if="scope.row.status == 0"
                        @click="release(scope.row)"
                        class="action-btn"
                      >
                        <Icon icon="ep:position" class="btn-icon" />
                        发布
                      </el-button>

                      <el-button
                        type="warning"
                        text
                        v-if="scope.row.status == 1"
                        @click="offline(scope.row)"
                        class="action-btn"
                      >
                        <Icon icon="ep:bottom" class="btn-icon" />
                        下线
                      </el-button>

                      <el-button type="danger" text @click="del(scope.row)" class="action-btn">
                        <Icon icon="ep:delete" class="btn-icon" />
                        删除
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div v-else class="empty-state">
              <div class="empty-illustration">
                <Icon icon="ep:connection" class="empty-icon" />
              </div>
              <h3 class="empty-title">暂无IVR流程</h3>
              <p class="empty-description">{{
                changeGroupItem ? '当前分组下暂无流程，点击上方按钮创建' : '请先选择分组'
              }}</p>
              <el-button
                v-if="changeGroupItem"
                type="primary"
                @click="addIvr"
                class="create-first-btn"
              >
                <Icon icon="ep:plus" class="btn-icon" />
                创建流程
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 弹窗组件 -->
  <AddGroupFrom ref="groupRefs" @success="getGroupList" />
  <AddIvrFrom ref="ivrRefs" @success="getIvrPage" />
</template>

<script setup>
import { Plus, Delete } from '@element-plus/icons-vue'
import * as ivrApi from '@/api/call/ivr/index.ts'
import AddGroupFrom from './components/addGroupFrom.vue'
import AddIvrFrom from './components/addIvrFrom.vue'
import { dateFormatter } from '@/utils/formatTime'
import { useIvrStore } from '@/store/modules/ivr'

defineOptions({ name: 'IVRManagement' })

const useStore = useIvrStore()
const router = useRouter()
const groupRefs = ref(null)
const ivrRefs = ref(null)
const groupList = ref([])
const ivrList = ref([])
const changeGroupItem = ref(null)
const treeRefs = ref(null)

const statusObj = {
  0: { label: '草稿', type: 'info' },
  1: { label: '已发布', type: 'success' },
  2: { label: '已下线', type: 'danger' }
}

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    0: 'ep:edit-pen',
    1: 'ep:check',
    2: 'ep:close'
  }
  return iconMap[status] || 'ep:question-filled'
}

// 发布
const release = (row) => {
  ElMessageBox.confirm('确定发布吗？', '发布确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await ivrApi.updateIvrFlow({
      id: row.id,
      status: 1
    })
    ElMessage.success('发布成功!')
    getIvrPage()
  })
}

// 下线
const offline = (row) => {
  ElMessageBox.confirm('确定要下线吗？', '下线确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await ivrApi.updateIvrFlow({
      id: row.id,
      status: 2
    })
    ElMessage.success('下线成功!')
    getIvrPage()
  })
}

// 删除
const del = (row) => {
  ElMessageBox.confirm('确定要删除吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await ivrApi.deleteIvrFlow(row.id)
    ElMessage.success('删除成功!')
    getIvrPage()
  })
}

// 删除分组
const delTree = (item) => {
  ElMessageBox.confirm('确定要删除吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await ivrApi.deleteIvrGroup(item.id)
    ElMessage.success('删除成功!')
    getGroupList()
  })
}

// 编辑
const edit = (row) => {
  useStore.initNodes()
  router.push({
    name: 'ivrEdit',
    query: {
      groupId: changeGroupItem.value.id,
      id: row.id
    }
  })
}

// 分组列表
const getGroupList = async () => {
  const data = await ivrApi.getIvrGroupPage()
  groupList.value = buildTree(data.list)
  nextTick(() => {
    if (groupList.value[0]) {
      changeGroupItem.value = groupList.value[0]
      treeRefs.value.setCurrentKey(groupList.value[0].id, true)
    }
  })
}

const handleCheckChange = (e) => {
  changeGroupItem.value = e
  ivrFlowPage(e.id)
}

const getIvrPage = () => {
  ivrFlowPage(changeGroupItem.value.id)
}

// 增加分组
const addGroup = () => {
  groupRefs.value.open(changeGroupItem.value)
}

// 增加ivr
const addIvr = () => {
  ivrRefs.value.open(changeGroupItem.value)
}

// 根据分组id查询流程列表
const ivrFlowPage = async (id) => {
  const data = await ivrApi.getIvrPage(id)
  ivrList.value = data.list
}

// 扁平化
const buildTree = (items) => {
  const map = {}
  const roots = []
  // 创建映射表
  items.forEach((item) => {
    map[item.id] = { ...item, children: [] }
  })
  // 构建树结构
  items.forEach((item) => {
    const parent = map[item.parentId]
    if (parent) {
      parent.children.push(map[item.id])
    } else if (item.parentId === 0) {
      roots.push(map[item.id])
    }
  })
  return roots
}

onMounted(() => {
  getGroupList()
})
</script>

<style lang="scss" scoped>
.ivr-management-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #97a5e2 0%, #7db5db 100%);
  border-radius: 16px;
  padding: 12px;
  margin-bottom: 12px;
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 150px;
    height: 150px;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
    border-radius: 50%;
  }
}

.header-content {
  position: relative;
  z-index: 1;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  backdrop-filter: blur(10px);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 14px;
  margin: 0;
  opacity: 0.9;
}

/* 主要布局 */
.main-layout {
  display: flex;
  gap: 24px;
  flex: 1;
  min-height: 0;
}

/* 左侧边栏 */
.sidebar-section {
  width: 300px;
  flex-shrink: 0;
}

.sidebar-content {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
}

.add-group-section {
  padding: 20px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
}

.add-group-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 16px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: white;
  color: #6b7280;
  font-size: 14px;
  font-weight: 500;

  &:hover {
    border-color: #0052cc;
    color: #0052cc;
    background: rgba(0, 82, 204, 0.02);
  }
}

.add-icon {
  font-size: 16px;
}

.tree-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tree-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
  background: linear-gradient(135deg, rgba(0, 82, 204, 0.02) 0%, transparent 100%);
}

.tree-header-icon {
  color: #0052cc;
  font-size: 16px;
}

.tree-title {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.tree-container {
  flex: 1;
  overflow: auto;
  padding: 16px 0;
}

.group-tree {
  padding: 0 20px;

  :deep(.el-tree-node__content) {
    height: 40px;
    border-radius: 8px;
    margin-bottom: 4px;
    transition: all 0.2s ease;

    &:hover {
      background: rgba(0, 82, 204, 0.05);
    }
  }

  :deep(.el-tree-node.is-current > .el-tree-node__content) {
    background: linear-gradient(135deg, rgba(0, 82, 204, 0.1) 0%, rgba(0, 82, 204, 0.05) 100%);
    border: 1px solid rgba(0, 82, 204, 0.2);
  }

  :deep(.el-tree-node__expand-icon) {
    color: #0052cc;
  }
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 8px;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.node-icon {
  color: #0052cc;
  font-size: 14px;
  flex-shrink: 0;
}

.node-title {
  font-size: 14px;
  color: #374151;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.node-actions {
  opacity: 0;
  transition: opacity 0.2s ease;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

.delete-btn {
  padding: 4px;
  border-radius: 4px;

  &:hover {
    background: rgba(239, 68, 68, 0.1);
  }
}

/* 右侧内容区 */
.content-section {
  flex: 1;
  overflow: hidden;
}

.content-wrapper {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
  background: linear-gradient(135deg, rgba(0, 82, 204, 0.02) 0%, transparent 100%);
}

.action-left {
  display: flex;
  align-items: center;
}

.current-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.group-icon {
  color: #0052cc;
  font-size: 18px;
}

.group-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.add-ivr-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

.table-section {
  flex: 1;
  overflow: hidden;
  padding: 24px;
}

.table-container {
  height: 100%;
  overflow: auto;
}

.ivr-table {
  :deep(.el-table__header) {
    background: rgba(0, 82, 204, 0.02);
  }

  :deep(.el-table__header th) {
    background: transparent;
    border-bottom: 1px solid rgba(0, 82, 204, 0.1);
    color: #374151;
    font-weight: 600;
  }

  :deep(.el-table__body tr:hover) {
    background: rgba(0, 82, 204, 0.02);
  }

  :deep(.el-table__body td) {
    border-bottom: 1px solid rgba(0, 82, 204, 0.05);
  }
}

.name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name-icon {
  width: 24px;
  height: 24px;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  flex-shrink: 0;
}

.name-text {
  font-weight: 500;
  color: #374151;
}

.desc-cell {
  color: #6b7280;
  font-size: 14px;
}

.status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 12px;
  font-weight: 500;
}

.tag-icon {
  font-size: 12px;
}

.creator-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
}

.creator-icon {
  color: #6b7280;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;

  .btn-icon {
    margin-right: 4px;
    font-size: 12px;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  padding: 40px;
}

.empty-illustration {
  margin-bottom: 24px;
}

.empty-icon {
  font-size: 80px;
  color: #d1d5db;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 8px 0;
}

.empty-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0 0 24px 0;
}

.create-first-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-layout {
    flex-direction: column;
    gap: 16px;
  }

  .sidebar-section {
    width: 100%;
    height: 300px;
  }
}

@media (max-width: 768px) {
  .ivr-management-container {
    padding: 12px;
  }

  .page-header {
    padding: 20px;
    margin-bottom: 16px;
  }

  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .table-section {
    padding: 16px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .ivr-management-container {
    background: linear-gradient(135deg, #1f2937 0%, #111827 100%);
  }

  .sidebar-content,
  .content-wrapper {
    background: rgba(30, 41, 59, 0.95);
  }

  .page-title {
    color: #f9fafb;
  }

  .tree-title,
  .group-name {
    color: #f9fafb;
  }

  .node-title,
  .name-text {
    color: #e5e7eb;
  }

  .empty-title {
    color: #f9fafb;
  }

  .empty-description {
    color: #d1d5db;
  }
}
</style>
